﻿// ExtensionMethods.cs
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Carto;
using System;
using System.Runtime.InteropServices;

namespace MapFormsApp.Helpers
{
    /// <summary>
    /// 几何操作扩展方法
    /// </summary>
    public static class GeometryExtensions
    {
        // 创建缓冲区（单位：米）
        public static IGeometry Buffer(this IGeometry geometry, double distance)
        {
            if (geometry == null) return null;
            ITopologicalOperator topo = geometry as ITopologicalOperator;
            return topo?.Buffer(distance);
        }

        // 获取几何中心点
        public static IPoint GetCentroid(this IGeometry geometry)
        {
            IArea area = geometry as IArea;
            if (area == null) return null;

            IPoint centroid = new PointClass();
            area.QueryCentroid(centroid);
            return centroid;
        }
    }

    /// <summary>
    /// 数据访问扩展方法
    /// </summary>
    public static class DataAccessExtensions
    {
        // 根据名称快速打开要素类
        public static IFeatureClass OpenFeatureClass(this IFeatureWorkspace workspace, string name)
        {
            return workspace.OpenFeatureClass(name);
        }

        // 安全执行编辑操作（自动处理事务）
        public static void ExecuteEditOperation(this IWorkspace workspace, Action editAction)
        {
            IWorkspaceEdit workspaceEdit = (IWorkspaceEdit)workspace;
            try
            {
                workspaceEdit.StartEditing(false);
                workspaceEdit.StartEditOperation();
                editAction?.Invoke();
                workspaceEdit.StopEditOperation();
                workspaceEdit.StopEditing(true);
            }
            catch
            {
                workspaceEdit.AbortEditOperation();
                workspaceEdit.StopEditing(false);
                throw;
            }
        }
    }

    /// <summary>
    /// 图层管理扩展方法
    /// </summary>
    public static class LayerExtensions
    {
        // 按名称查找图层
        public static ILayer FindLayerByName(this IMap map, string layerName)
        {
            for (int i = 0; i < map.LayerCount; i++)
            {
                if (map.get_Layer(i).Name.Equals(layerName, StringComparison.OrdinalIgnoreCase))
                {
                    return map.get_Layer(i);
                }
            }
            return null;
        }

        // 将要素类快速转换为图层
        public static IFeatureLayer ToFeatureLayer(this IFeatureClass featureClass, string layerName = null)
        {
            IFeatureLayer featureLayer = new FeatureLayerClass();
            featureLayer.FeatureClass = featureClass;
            featureLayer.Name = string.IsNullOrEmpty(layerName) ? featureClass.AliasName : layerName;
            return featureLayer;
        }
    }

    /// <summary>
    /// COM对象管理扩展方法
    /// </summary>
    public static class ComObjectExtensions
    {
        // 安全释放COM对象
        public static void SafeRelease(this object comObject)
        {
            if (comObject != null && Marshal.IsComObject(comObject))
            {
                Marshal.ReleaseComObject(comObject);
            }
        }

        // 自动管理游标生命周期
        public static void UsingCursor(this IFeatureCursor cursor, Action<IFeatureCursor> action)
        {
            try
            {
                action(cursor);
            }
            finally
            {
                Marshal.ReleaseComObject(cursor);
            }
        }
    }

    /// <summary>
    /// 地图控件扩展方法
    /// </summary>
    public static class MapControlExtensions
    {
        // 屏幕坐标转地图坐标
        public static IPoint ToMapPoint(this ESRI.ArcGIS.Controls.IMapControl3 mapControl, int x, int y)
        {
            return mapControl.ActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(x, y);
        }

        // 添加图层并自动刷新
        public static void AddLayerWithRefresh(this ESRI.ArcGIS.Controls.IMapControl3 mapControl, ILayer layer)
        {
            mapControl.Map.AddLayer(layer);
            mapControl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null);
        }
    }

    /// <summary>
    /// 随机数据生成扩展方法（测试用）
    /// </summary>
    public static class RandomDataExtensions
    {
        private static readonly Random _random = new Random();

        // 生成随机点
        public static IPoint GenerateRandomPoint(this IEnvelope envelope)
        {
            double x = envelope.XMin + (envelope.XMax - envelope.XMin) * _random.NextDouble();
            double y = envelope.YMin + (envelope.YMax - envelope.YMin) * _random.NextDouble();
            return new PointClass() { X = x, Y = y };
        }
    }
}